package com.xmcowell.sportpacemaster.utils;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.xmcowell.sportpacemaster.config.Contents;

import java.util.ArrayList;

/**
 * Created by fanyingmao on 16/11/6.
 */
public class MyThread implements Runnable {
    private final int rushDaly = 1000;//刷新率
    private Boolean isStop = true;
    private Boolean isFinish = false;
    private Handler mHandler;
    private int runTimes = 0;
    private ArrayList<MyEvent> listMyEvent;
    public Context context;

    public MyThread(Context context, Handler mHandler) {
        this.context = context;
        this.mHandler = mHandler;
        listMyEvent = new ArrayList<>();
    }

    @Override
    public void run() {
        Log.e("MyThread", "运行MyThread线程");
        while (!isFinish) {
            try {
                Thread.sleep(rushDaly);
            } catch (InterruptedException e) {
                e.printStackTrace();
                break;
            }
            if (!isStop) {
                runTimes += rushDaly / 1000;
//                Log.e("MyThread", "计算,当前时间runTimes = "+getTime());
                for (int i = 0; i < listMyEvent.size(); i++) {
                    dealEvent(listMyEvent.get(i));
                }
                mHandler.sendEmptyMessage(Contents.WHAT_TIME_UI);
            }
        }
    }

    private void dealEvent(MyEvent mMyEvent) {
        if (mMyEvent.isCycle()) {

        } else {
            if (runTimes == mMyEvent.getSendTime()) {
                if (mMyEvent.getObj() != null) {
                    Message msg = new Message();
                    msg.what = mMyEvent.getWhat();
                    msg.obj = mMyEvent.getObj();
                    mHandler.sendMessage(msg);
                } else {
                    mHandler.sendEmptyMessage(mMyEvent.getWhat());
                }
            }
        }
    }

    public void stop() {
        isStop = true;
    }

    public void start() {
        runTimes = 0;
        isStop = false;
    }

    public boolean isStop() {
        return isStop;
    }

    public void finish() {
        isFinish = true;
    }

    public int getTime() {
        return runTimes;
    }

    public void resetTime() {
        runTimes = 0;
        isStop = false;
    }
}
